// RegisterController.java
package com.controller;

import com.entity.Users;
import com.mapper.UsersMapper;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class RegisterController {

    @Autowired
    private UsersMapper usersMapper;

    @GetMapping("/register")
    public String registerPage() {
        return "/client/register";
    }

    @PostMapping("/toRegister")
    public String toRegister(Users users) {
        // 检查用户名是否已存在
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(Users::getUsername, users.getUsername());
        Users existingUser = usersMapper.selectOneByQuery(queryWrapper);

        if (existingUser != null) {
            // 用户名已存在，返回注册页面并提示错误
            return "/client/register";
        } else {
            // 用户名不存在，执行注册
            usersMapper.insertSelective(users);
            // 注册成功后重定向到登录页面
            return "redirect:/login";
        }
    }
}
